package com.sc.file;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Shen Chao on 2018-12-22-022.
 */
public class FileDirCheck {

    private List<String> resultList = new LinkedList<>();
    private LinkedList<File> list = new LinkedList<>();

    public List<String> traverseFolder1(String path) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            try {
                if (null == files || files.length == 0) {
                    System.out.println(file.getAbsolutePath() + "文件夹是空的!");
                } else {
                    forFile(files);

                    File temp_file;
                    while (!list.isEmpty()) {
                        temp_file = list.removeFirst();
                        files = temp_file.listFiles();
                        forFile(files);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("文件不存在!");
        }
        return resultList;
    }

    private void forFile(File[] files) {
        for (File file2 : files) {
            if (file2.isDirectory()) {
                list.add(file2);
            } else {
                try {
                    String fileMD5String= MD5Util.getFileMD5String(file2) + "-" + file2.getAbsolutePath();
                    resultList.add(fileMD5String);
                    System.out.println(fileMD5String);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public List<String> traverseFolder2(String path) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                System.out.println(file.getAbsolutePath() + "文件夹是空的!");
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
//                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        traverseFolder2(file2.getAbsolutePath());
                    } else {
                        //md5校验文件是否相同
                        try {
//                            System.out.println("文件:" + file2.getAbsolutePath());
                            String fileMD5String = MD5Util.getFileMD5String(file2) + "-" + file2.getAbsolutePath();
//                            System.out.println(fileMD5String);
                            resultList.add(fileMD5String);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
        return resultList;
    }
}
